<template>
	<view>
		<view class="pad-0-16r">
			<CheckBranchVue></CheckBranchVue>
		</view>
		<UserInfoCardVue></UserInfoCardVue>
		<tabs :activeTab="activeTab" :tabList="tabList" @change-tab="onChangeTab" />
		<searchBtnVue v-if="activeTab!='history'" @search='onSearch' placeholder="搜索关键字"></searchBtnVue>
		<view class="self-billing" v-if="activeTab!='history'">
			<view class="main-content">
				<view class="category-container">
					<!-- 左侧分类 -->
					<view class="category-list">
						<view v-for="(item, index) in categories" :key="index"
							:class="['category-item', index === activeCategory ? 'active' : '']"
							@click="changeCategory(item,index)">
							<view class="mar-0-5">{{ item.name }}</view>
						</view>
					</view>
				</view>

				<view class="item-container">
					<!-- 右侧项目 -->
					<view class="item-list">
						<view v-for="(item, idx) in childItems" :key="item.idx" class="item-row">
							<radio :checked="item.checked" @click="changeRedio(item)" class="small-radio" />
							<view class="item-info">
								<view class="item-name start-center">
									<view>{{ item.name }}</view>
									<text class="item-en" v-if="item.en">({{ item.en }})</text>
								</view>
								<view class="item-info-bottom">
									<view class="item-price">￥{{ item.money }}</view>
									<view class="notice-btn" @click="changeModel(item)">注意事项</view>
								</view>
							</view>
						</view>
					</view>
				</view>
				<u-popup v-model="showModel" mode="bottom" length="60%">
					<view class="pad-10">
						<view class="title">{{item.name}}</view>
						<view class="color-red mar-5-0">￥{{item.money}}</view>
						<view class="border-col"></view>
						<view class="item-describe">
							<view class="font-weight">注意事项</view>
							<view>
								<text>{{item.describe}}</text>
							</view>
						</view>
					</view>
				</u-popup>
			</view>
		</view>
		<!-- 	<main-content v-if="activeTab!='history'" :items="items" :activeTab="activeTab" ref="refChild"
				:search-key="searchKey" @toggle-item="toggleItem" /> -->
		<!-- <RecordVue v-if="activeTab=='history'"></RecordVue> -->
		<view class="pad-10" v-if="activeTab=='history'">
			<RecordVue :dataSource="dataSource" @onChangeTab="onChangeTab"></RecordVue>
			<!-- 开单记录 -->

		</view>
		<footer-bar v-if="activeTab!='history'" :total-num="totalNum" :total-price="totalPrice"
			@toggle-selected-list="showSelectedListModal = !showSelectedListModal" @submit="openDialog" />

		<view v-if="showSelectedListModal && activeTab!='history'" class="selected-list-modal">
			<view class="modal-header">
				<view>已选列表</view>
				<view class="clear-btn" @click.stop="clearSelectedList">清空列表</view>
			</view>
			<view v-for="(item, idx) in selectedItems" :key="idx" class="selected-item">
				<u-icon name="checkmark-circle-fill" color="#1cb7d6" size="32rpx" />
				<view class="item-info">
					<view class="item-name">{{ item.name }}<text v-if="item.en">（{{ item.en }}）</text></view>
					<view class="item-bottom">
						<view class="item-price">￥{{ item.money.toFixed(2) }}</view>
						<view class="item-count">数量：X 1</view>
					</view>
				</view>
			</view>
		</view>

		<Dialog :show="showDialogModal" @confirm="confirm" @close="showDialogModal = false" title="温馨提示"
			:mask-close-able="true">
			<view class="slot-content">
				<view class="text-center">
					<rich-text :nodes="'提交后无法更改，如需更改，请重新申请'"></rich-text>
				</view>
			</view>
		</Dialog>

		<u-toast ref="uToast" />
		<LoadVue :load="load"></LoadVue>
	</view>
</template>

<script>
	import tabs from './components/tabs.vue'

	import FooterBar from './components/SelfBilling/footerBar.vue'
	import {
		mapGetters,
		mapActions
	} from 'vuex'
	import Dialog from '../../../components/Dialog/Dialog.vue'
	import CheckBranchVue from '@/components/checkBranch/checkBranch.vue'
	import UserInfoCardVue from '../../../components/UserInfo/UserInfoCard.vue'
	import RecordVue from './components/SelfBilling/record.vue'
	import {
		selfBillingAddBatch,
		selfBillingSelect,
	} from '../../../api/selfBilling'
	import {
		selfBillingProjectSelect
	} from '../../../api/SelfBillingProject'
	import searchBtnVue from '../../../components/Search/searchBtn.vue'
	import ButtonAllVue from '../../../components/Button/ButtonAll.vue'
	import {

		dateFormat,
	} from '../../../utils/assist'
	export default {
		components: {
			UserInfoCardVue,
			tabs,
			CheckBranchVue,
			RecordVue,
			FooterBar,
			Dialog,
			searchBtnVue,
			ButtonAllVue,
		},
		data() {
			return {
				tabList: [{
						label: '检验',
						value: '05'
					},
					{
						label: '检查',
						value: '06'
					},
					{
						label: '开单记录',
						value: 'history'
					},
				],
				activeTab: '05',
				searchKey: '',
				categories: [],
				items: [],
				showSelectedListModal: false,
				showDialogModal: false,

				activeCategory: 0,
				categories: [],
				childItems: [],
				showModel: false,
				item: {},
				list: [], //被选中之前的项目
				listTemp: [], //被选中之后的项目
				dataSource: [],
				load: false
			}
		},
		computed: {
			...mapGetters([
				'userInfo', 'currentHospitalInfo'
			]),
			totalPrice() {
				return this.items.filter(i => i.checked).reduce((sum, i) => sum + i.money, 0).toFixed(2);
			},
			totalNum() {
				return this.items.filter(i => i.checked).length;
			},
			selectedItems() {
				return this.items.filter(i => i.checked);
			}
		},
		onLoad(e) {
			let item = e.item
			if (item) {
				let data = JSON.parse(e.item)
				this.activeTab = data.activeTab
				this.preId = data.preId;
				this.initHistory()
			} else {
				this.init()
			}
		},
		mounted() {

		},
		methods: {
			onChangeTab(tab) {
				this.activeTab = tab;
				console.log(tab)
				if (tab == 'history') {
					this.preId = ''
					this.initHistory()
				} else {
					this.init()
				}
			},
			onSearch(key) {
				this.searchKey = key;
				console.log(this.searchKey)
				this.init()
			},
			clearSelectedList() {
				this.items.forEach(i => {
					i.checked = false
				});
				this.init()
			},
			openDialog() {
				if (this.items.length == 0) {
					this.$u.toast("没有开单项目");
					return;
				} else {
					this.showDialogModal = true
				}
			},
			init() {
				this.listTemp = []
				this.categories = []
				this.childItems = []
				this.load = false,
					// 查询自助开单项目
					selfBillingProjectSelect({
						medicalType: this.activeTab,
						name: this.searchKey
					}).then(res => {
						console.log(res)
						if (res.length > 0) {
							this.categories = res;
							this.changeCategory(this.categories[0], 0)
						}

					}).finally(() => {
						this.load = false
					})
			},
			initHistory() {
				if (!this.userInfo) {
					this.$u.toast('请选择就诊卡')
					return;
				}
				this.load = true
				selfBillingSelect({
					patId: this.userInfo.patId,
					preId: this.preId,
					orderBy: "id desc"
				}).then(res => {
					console.log(res)
					if (res.length > 0) {
						res.forEach(item => {
							if (item.visitTime) {
								item.visitTime = dateFormat("yyyy-MM-dd", new Date(item.visitTime))
							}
						})
					}
					this.dataSource = res || [];
				}).finally(() => {
					this.load = false
				})
			},
			changeCategory(item, index) {
				let itemTemp = {
					...item
				}
				this.activeCategory = index
				this.childItems = []
				// 默认所有的都未选中
				if (itemTemp.child) {
					let list = itemTemp.child;
					list.forEach(item => {
						item.checked = false
					})
					this.childItems = list
				} else {
					itemTemp.checked = false;
					this.childItems.push({
						...itemTemp
					})
				}
				// 将当前的项目和已经选中的项目进行比较，如果有，则当前radio选中状态
				for (var i = 0; i < this.listTemp.length; i++) {
					for (var j = 0; j < this.childItems.length; j++) {
						if (this.childItems[j].id == this.listTemp[i].id) {
							this.childItems[j].checked = true
						}
					}
				}
			},
			changeModel(item) {
				this.showModel = true
				this.item = item;
			},
			changeRedio(item) {
				item.checked = !item.checked
				this.listTemp = []
				this.list.push({
					...item
				})
				if (this.list.length > 1) {
					for (var i = 0; i < this.list.length; i++) {
						if (this.list[i].id == item.id && !item.checked) {

						} else {
							this.listTemp.push(this.list[i])
						}
					}
				} else {
					this.listTemp = this.list
				}
				this.list = this.listTemp
				this.items = this.listTemp
			},
			confirm() {
				this.items.forEach(item => {
					item.patId = this.userInfo.patId
					item.patName = this.userInfo.patName
					item.execDeptCode = item.departmentCode
					item.execDeptName = item.departmentName
					item.execDoctorCode = item.doctorCode
					item.execDoctorName = item.doctorName
					item.campusCode = this.currentHospitalInfo.code
					item.campusName = this.currentHospitalInfo.name

				})
				console.log(this.items)
				// 批量开单
				selfBillingAddBatch({
					list: this.items
				}).then(res => {
					console.log(res)
					if (res) {
						this.$u.toast(res + " 已经开单")
						return;
					} else {
						this.onChangeTab("history")
						this.items = []
					}

				})
				this.showDialogModal = false
			},
		}
	}
</script>

<style scoped>
	.self-billing {
		background: linear-gradient(#e0f3ff 0%, #fff 30%);
		/* min-height: 100vh; */
		/* display: flex; */
		/* flex-direction: column; */
	}

	.userCard {
		margin: 0 24rpx;
	}

	.selected-list-modal {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 130rpx;
		background: #fff;
		border-radius: 24rpx 24rpx 0 0;
		box-shadow: 0 -2rpx 16rpx #eee;
		z-index: 666;
		padding: 32rpx 24rpx 24rpx 24rpx;
		max-height: 70vh;
		overflow-y: auto;
	}

	.modal-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 24rpx;
	}

	.clear-btn {
		background: none;
		color: #1cb7d6;
		border: 1px solid #1cb7d6;
		border-radius: 26rpx;
		font-size: 26rpx;
		padding: 0 16rpx;
	}

	.selected-item {
		display: flex;
		align-items: center;
		background: #f8f8f8;
		border-radius: 12rpx;
		padding: 18rpx 16rpx;
		margin-bottom: 16rpx;
	}

	.selected-item .item-info {
		flex: 1;
		margin-left: 16rpx;
	}

	.item-name {
		font-size: 28rpx;
		color: #222;
	}

	.item-bottom {
		display: flex;
		justify-content: space-between;
	}

	.item-price {
		color: #ff5a5f;
		font-size: 26rpx;
		margin: 4rpx 0;
	}

	.item-count {
		color: #888;
		font-size: 24rpx;
		margin-bottom: 4rpx;
	}

	.border-col {
		width: 100%;
		height: 1px;
		border-bottom: 1px solid rgb(215, 215, 215);
		margin: 5px 0;
	}

	.title {
		font-weight: bold;
	}

	.main-content {
		display: flex;
		height: calc(100vh - 430rpx - 130rpx);
		overflow: hidden;
		margin-bottom: 130rpx;
	}

	.category-container {
		width: 250rpx;
		height: 100%;
		overflow-y: auto;
		background: #F6F6F6;
		border-radius: 16rpx 0 0 0;
	}

	.category-list {
		height: 100%;
		-webkit-overflow-scrolling: touch;
	}

	.item-container {
		flex: 1;
		height: 100%;
		overflow: auto;
		background: #fff;
		border-radius: 0 16rpx 0 0;
	}

	.item-list {
		height: 100%;
		padding: 0 24rpx;
		overflow-y: auto;
	}

	.category-item {
		padding: 24rpx 0;
		text-align: center;
		color: #666;
		font-size: 28rpx;
		background: #F6F6F6;
		position: relative;
		line-height: 44rpx;
	}

	.category-item.active {
		color: #1cb7d6;
		font-weight: bold;
		background: #fff;
	}

	.category-item.active::before {
		content: '';
		display: block;
		position: absolute;
		width: 6rpx;
		height: 64rpx;
		left: 0;
		top: 50%;
		transform: translateY(-50%);
		background: #1cb7d6;
		border-radius: 4rpx 0 0 4rpx;
	}

	.item-row {
		display: flex;
		align-items: flex-start;
		border-bottom: 1px solid #f2f3f5;
		padding: 32rpx 0;
	}

	.small-radio {
		transform: scale(0.7);
	}

	.item-info {
		flex: 1;
	}

	.item-name {
		font-size: 30rpx;
		color: #222;
	}

	.item-info-bottom {
		width: 360rpx;
		display: flex;
		justify-content: space-between;
	}

	.item-en {
		font-size: 24rpx;
		color: #aaa;
		margin-left: 8rpx;
	}

	.item-price {
		color: #ff5a5f;
		font-size: 28rpx;
		margin-top: 8rpx;
	}

	.notice-btn {
		background: #f0faff;
		color: #1ec6e6;
		border: none;
		border-radius: 26rpx;
		font-size: 24rpx;
		padding: 4rpx 20rpx;
		margin: 10rpx 20rpx 0;
	}

	.base-title {
		width: 80px;
		text-align: justify;
		line-height: 30px;
		text-align-last: justify;
	}

	.item {
		margin: 10px 0;
		background: #fafafa;
		padding: 10px;
		border-radius: 10px;
	}
</style>